package com.yxjx.duoxue.my;

import java.io.IOException;
import java.util.ArrayList;

import org.apache.http.client.ClientProtocolException;
import org.json.JSONException;
import org.json.JSONObject;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;

import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.listener.PauseOnScrollListener;
import com.yxjx.duoxue.BaseActionBarActivity;
import com.yxjx.duoxue.HomePageActivity;
import com.yxjx.duoxue.R;
import com.yxjx.duoxue.Yx;
import com.yxjx.duoxue.activities.ActivitiesPageFragment;
import com.yxjx.duoxue.activities.ActivityIntroductionActivity;
import com.yxjx.duoxue.course.CourseIntroductionActivity;
import com.yxjx.duoxue.course.CourseListActivity;
import com.yxjx.duoxue.customview.autolist.AutoListView;
import com.yxjx.duoxue.customview.autolist.AutoListView.OnLoadListener;
import com.yxjx.duoxue.customview.autolist.AutoListView.OnRefreshListener;
import com.yxjx.duoxue.datamodel.DMActivity;
import com.yxjx.duoxue.datamodel.course.DMCourse;
import com.yxjx.duoxue.network.NwUtils;
import com.yxjx.duoxue.network.UserLoginResponse;
import com.yxjx.duoxue.network.UserReg;
import com.yxjx.duoxue.utils.UIHelper;
import com.yxjx.duoxue.utils.Utils;

public class RegisteredActivitiesPage extends BaseActionBarActivity implements
		OnRefreshListener, OnLoadListener {
	
	public static final int PAGE_ACTIVITY_NUM = 20;

	private RegisteredActivitiesAdapter mAdapter;
	protected UserLoginResponse mULrsp;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.fragment_reg_activities);
		
		mList = (AutoListView) findViewById(R.id.list);
		mAdapter = new RegisteredActivitiesAdapter();
		mList.setAdapter(mAdapter);
		mList.setOnRefreshListener(this);
		mList.setOnLoadListener(this);
		mList.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
					long arg3) {
				
				if (arg2 >= mAdapter.getCount() + 1 || arg2 == 0) {
					return;
				}
				
				DMActivity activity = mAdapter.getData().get(arg2 - 1);
				Intent intent = new Intent(getApplicationContext(), ActivityIntroductionActivity.class);
				intent.putExtra(Yx.EXTRA_DM_ACTIVITY_ID, "" + activity.getActivityId());
				startActivity(intent);
			}
		});

		customizeActionBarTitle("报名活动");
//		UIHelper.setClickListener(findViewById(R.id.root), R.id.more_activities, mClickListener);
		
		requestAllActivities();
	}
	
	private void requestAllActivities() {
		requestActiviitesByParams(0, AutoListView.REFRESH);
	}
	
	private void requestMoreActivities() {
		int startIndex = mAdapter.getCount() + 1;
		requestActiviitesByParams(startIndex, AutoListView.LOAD);
	}

	private void requestActiviitesByParams(final int startIndex, final int callbackId) {
		
		new Thread(new Runnable() {
			
			@Override
			public void run() {
				JSONObject params = new JSONObject();
				try {
					params.put("startIndex", "" + startIndex);
					params.put("count", "20");
				} catch (JSONException e) {
					e.printStackTrace();
				}
				
				mULrsp = UserLoginResponse.getInstance(getApplicationContext());

				// book info list. 
				ArrayList<DMActivity> activities = new ArrayList<DMActivity>();
				try {
					activities = UserReg.requestBookedInfos(mULrsp, null, Yx.TYPE_ITEM_ACTIVITY, params, RegisteredActivitiesPage.this);
				} catch (ClientProtocolException e) {
					e.printStackTrace();
				} catch (JSONException e) {
					e.printStackTrace();
				} catch (IOException e) {
					e.printStackTrace();
				}
				
				mHandler.sendMessage(mHandler.obtainMessage(callbackId, activities));
				
			}
		}).start();
	}
	
	
	
	private Handler mHandler = new Handler() {
    	@Override
    	public void handleMessage(android.os.Message msg) {
    		ArrayList<DMActivity> result = (ArrayList<DMActivity>) msg.obj;
    		
    		switch (msg.what) {
			case AutoListView.REFRESH:
				removeMessages(AutoListView.REFRESH);
				mAdapter.setDatas(result);
				mList.onRefreshComplete();
				// try to progress dialog
				dismissDialog(result);
				resetScroll();
				break;
			case AutoListView.LOAD:
				removeMessages(AutoListView.LOAD);
				mAdapter.addData(result);
				mList.onLoadComplete();
				break;
			default:
				break;
			}
    		if (result == null) {
    			mList.setResultSize(0);
    		} else {
    			mList.setResultSize(result.size());
    		}
    		
    	}
    };
    
	private void dismissDialog(ArrayList<DMActivity> data) {
		findViewById(R.id.loading).setVisibility(View.INVISIBLE);
		if (data == null || data.size() == 0) {
			findViewById(R.id.empty).setVisibility(View.VISIBLE);
		} else {
			findViewById(R.id.list).setVisibility(View.VISIBLE);
		}
	}

	class RegisteredActivitiesAdapter extends BaseAdapter {
		
		private ArrayList<DMActivity> mDatas = new ArrayList<DMActivity>();
		
		public ArrayList<DMActivity> getData() {
			return mDatas;
		}
		
		@Override
		public int getCount() {
			if (mDatas == null || mDatas.size() == 0) {
				return 0;
			}
			return mDatas.size();
		}

		@Override
		public Object getItem(int arg0) {
			return null;
		}

		@Override
		public long getItemId(int arg0) {
			return 0;
		}

		@Override
		public View getView(int arg0, View arg1, ViewGroup arg2) {
			View ret;
			if (arg1 == null) {
				ret = LayoutInflater.from(getApplicationContext()).inflate(R.layout.item_course_list, null);
			} else {
				ret = arg1;
			}
			DMActivity activity = mDatas.get(arg0);
			
			UIHelper.setText(ret, R.id.course_name, activity.getActivityName());
			UIHelper.setText(ret, R.id.category, activity.getHostName());
			UIHelper.setText(ret, R.id.school_name, Utils.getTimeDuration(activity.getStartTime(), activity.getEndTime()));
			((TextView) ret.findViewById(R.id.location_info)).setVisibility(View.INVISIBLE);
			ret.findViewById(R.id.rating_bar).setVisibility(View.GONE);
			// setText(Utils.getDistanceDesc(getApplicationContext(), activity.getSchoolGps()));
			UIHelper.asyncLoadImage((ImageView) ret.findViewById(R.id.icon), activity.getHeadImageUrl(), R.drawable.default_icon);
			UIHelper.setText(ret, R.id.visit_count, "");
			return ret;
		}

		public ArrayList<DMActivity> getDatas() {
			return mDatas;
		}

		public void setDatas(ArrayList<DMActivity> mDatas) {
			this.mDatas = mDatas;
			notifyDataSetChanged();
		}
		
		public void addData(ArrayList<DMActivity> mDatas) {
			this.mDatas.addAll(mDatas);
			notifyDataSetChanged();
		}
	}
	
	private View.OnClickListener mClickListener = new View.OnClickListener() {
		
		@Override
		public void onClick(View arg0) {
			switch(arg0.getId()) {
			case R.id.more_activities:
				//
				Intent intent = new Intent(getApplicationContext(), HomePageActivity.class);
				// 活动的tab页面。
				intent.putExtra(Yx.KEY_HOME_TAB_INDEX, 1);
//				startActivity(intent);
				// do nothing
				break;
			default:
				mBaseClickListener.onClick(arg0);
				break;
			}
			
		}
	};
	
	private void resetScroll() {
		mList.post(new Runnable() {
			
			@Override
			public void run() {
				mList.setSelection(0);
			}
		});
	}

	private AutoListView mList;

	@Override
	public void onLoad() {
		requestMoreActivities();
	}

	@Override
	public void onRefresh() {
		requestAllActivities();
	}

}
